package com.sunyard.manage.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sunyard.dal.bo.*;
import com.sunyard.dal.bo.device.lock.LogBO;
import com.sunyard.dal.bo.log.OperateHistoryBO;
import com.sunyard.dal.bo.log.SysLogBO;
import com.sunyard.dal.bo.warning.NotWorkingTimeBO;
import com.sunyard.dal.dto.NotWorkingTimeDTO;
import com.sunyard.dal.dto.OperateHistoryDTO;
import com.sunyard.dal.dto.SysLogQueryDTO;
import com.sunyard.dal.entity.SysLog;
import com.sunyard.dal.mapper.OperateHistoryMapper;
import com.sunyard.dal.mapper.OrganizationMapper;
import com.sunyard.dal.mapper.SystemLogMapper;
import com.sunyard.manage.service.OperatorLogService;
import com.sunyard.redisUtil.RedisUtils;
import com.sunyard.utils.DateUtil;
import com.sunyard.utils.Response.BaseResult;
import com.sunyard.utils.Response.GetResult;
import com.sunyard.utils.TokenUtil;
import com.sunyard.utils.manage.DataGrid;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Transactional(rollbackFor = Exception.class)
@Service
public class OperatorLogServiceImpl implements OperatorLogService {


    @Autowired
    private SystemLogMapper systemLogMapper;
    @Autowired
    private OperateHistoryMapper operateHistoryMapper;
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public Integer insert(String operationDesc, String logName, String logStatus, String opId, String opName, String orgId) {
        SysLog sysLog = new SysLog();
        sysLog.setOperationDesc(operationDesc);
        sysLog.setLogName(logName);
        sysLog.setLogStatus(logStatus);
        sysLog.setOpId(opId);
        sysLog.setOpName(opName);
        sysLog.setOrgId(orgId);
        sysLog.setCreateDatetime(DateUtil.getDateStr(DateUtil.YYYYMMDD_HHMMSS, new Date()));
        return systemLogMapper.insert(sysLog);
    }

    @Override
    public Integer aspectInsert(SysLog operateLog) {
        return systemLogMapper.insert(operateLog);
    }

    /**
     * @return
     * @throws Exception
     * @Description:查询日志
     * @parm operatorLog
     */
    @Override
    public BaseResult<DataGrid<SysLogQueryDTO>> querySysLog(PaginationBO<SysLogBO> sysLogQuery, HttpServletRequest request) throws Exception {
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        SysLogBO sysLogBO = sysLogQuery.getParams();
        sysLogBO.setOrgId(orgId);
        // 设置分页信息
        PageHelper.startPage(sysLogQuery.getPageNo(), sysLogQuery.getPageSize());
        // 执行查询
        List<SysLogQueryDTO> list = systemLogMapper.getListSysLog(sysLogBO);
        // 取分页信息
        PageInfo<SysLogQueryDTO> pageInfo = new PageInfo<>(list);
        //设置返回结果
        DataGrid<SysLogQueryDTO> dataGrid = new DataGrid<>();
        long total = pageInfo.getTotal();
        dataGrid.setTotal((int) total);
        dataGrid.setRows(list);
        return GetResult.getResult(dataGrid);
    }

    @Override
    public BaseResult<DataGrid<OperateHistoryDTO>> queryHistory(PaginationBO<OperateHistoryBO> historyBOPaginationBO, HttpServletRequest request) throws Exception {
        //String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        OperateHistoryBO operateHistoryBO = historyBOPaginationBO.getParams();
        if (StringUtils.isNotBlank(operateHistoryBO.getStartDateTime())) {
            operateHistoryBO.setStartDateTime(DateUtil.DateToStr(DateUtil.YYYYMMDDHHMMSS,DateUtil.getDate(DateUtil.YYYYMMDD_HHMMSS,operateHistoryBO.getStartDateTime() + " 00:00:00")));
        }
        if (StringUtils.isNotBlank(operateHistoryBO.getEndDateTime())) {
            operateHistoryBO.setEndDateTime(DateUtil.DateToStr(DateUtil.YYYYMMDDHHMMSS,DateUtil.getDate(DateUtil.YYYYMMDD_HHMMSS,operateHistoryBO.getEndDateTime() + " 23:59:59")));
        }
        //获取当前机构及下属机构id集合
        List<String> orgIds = getListOrgIds(operateHistoryBO.getOrgId());
        orgIds.add(operateHistoryBO.getOrgId());
        operateHistoryBO.setOrgIds(orgIds);
        // 设置分页信息
        PageHelper.startPage(historyBOPaginationBO.getPageNo(), historyBOPaginationBO.getPageSize());
        // 执行查询
        List<OperateHistoryDTO> list = operateHistoryMapper.getHistoryLog(operateHistoryBO);
        // 取分页信息
        PageInfo<OperateHistoryDTO> pageInfo = new PageInfo<>(list);
        //设置返回结果
        DataGrid<OperateHistoryDTO> dataGrid = new DataGrid<>();
        long total = pageInfo.getTotal();
        dataGrid.setTotal((int) total);
        dataGrid.setRows(list);
        return GetResult.getResult(dataGrid);
    }

    @Override
    public BaseResult<DataGrid<NotWorkingTimeDTO>> getNotWorkingTimeLog(PaginationBO<NotWorkingTimeBO> notWorkingTimeBOPaginationBO, HttpServletRequest request) {
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        NotWorkingTimeBO notWorkingTimeBO = notWorkingTimeBOPaginationBO.getParams();
        if (StringUtils.isNotBlank(notWorkingTimeBO.getStartDateTime())) {
            notWorkingTimeBO.setStartDateTime(DateUtil.DateToStr(DateUtil.YYYYMMDDHHMMSS,DateUtil.getDate(DateUtil.YYYYMMDD_HHMMSS,notWorkingTimeBO.getStartDateTime() + " 00:00:00")));
        }
        if (StringUtils.isNotBlank(notWorkingTimeBO.getEndDateTime())) {
            notWorkingTimeBO.setEndDateTime(DateUtil.DateToStr(DateUtil.YYYYMMDDHHMMSS,DateUtil.getDate(DateUtil.YYYYMMDD_HHMMSS,notWorkingTimeBO.getEndDateTime() + " 23:59:59")));
        }
        //获取当前机构及下属机构id集合
        if (!StringUtils.isEmpty(notWorkingTimeBO.getOrgId())){
            orgId = notWorkingTimeBO.getOrgId();
        }
        List<String> orgIds = getListOrgIds(orgId);
        orgIds.add(orgId);
        notWorkingTimeBO.setOrgIds(orgIds);
        // 设置分页信息
        PageHelper.startPage(notWorkingTimeBOPaginationBO.getPageNo(), notWorkingTimeBOPaginationBO.getPageSize());
        // 执行查询
        List<NotWorkingTimeDTO> list = operateHistoryMapper.getNotWorkingTimeLog(notWorkingTimeBO);
        // 取分页信息
        PageInfo<NotWorkingTimeDTO> pageInfo = new PageInfo<>(list);
        //设置返回结果
        DataGrid<NotWorkingTimeDTO> dataGrid = new DataGrid<>();
        long total = pageInfo.getTotal();
        dataGrid.setTotal((int) total);
        dataGrid.setRows(list);
        return GetResult.getResult(dataGrid);
    }

    @Override
    public BaseResult uploadSysLog(LogBO bo) {
        SysLog sysLog = new SysLog();
        sysLog.setOperationDesc(bo.getOperationDesc());
        sysLog.setLogName(bo.getLogName());
        sysLog.setLogStatus(bo.getLogStatus());
        sysLog.setOpId(bo.getOpId());
        sysLog.setOpName(bo.getOpName());
        sysLog.setOrgId(bo.getOrgId());
        sysLog.setCreateDatetime(DateUtil.getDateStr(DateUtil.YYYYMMDD_HHMMSS, new Date()));
        Integer i = systemLogMapper.insert(sysLog);
        if(i<1){
            return GetResult.getResultFail("上传系统日志失败");
        }
        return  GetResult.getResultSuccess("上传系统日志成功");
    }


    public List<String> getListOrgIds(String orgId) {
        String strkey = "orgid:" + orgId;
        List<String> lists = null;
        lists = redisUtils.get(strkey, List.class);
        if (lists == null) {
            lists = new ArrayList<>();
            recursiveGetOrgId(lists, orgId);
        }
        redisUtils.set(strkey,lists);
        return lists;
    }

    //递归查询子机构
    private void recursiveGetOrgId(List<String> lists, String orgId) {
        List<String> orgIdList = organizationMapper.getOrgIdsList(orgId);
        while (orgIdList.size() == 0) {
            return;
        }
        //for (String childOrgId: orgIdList) {
        //    lists.add(childOrgId);
        //    recursiveGetOrgId(lists,childOrgId);
        //}

        orgIdList.forEach(childOrgId -> {
            lists.add(childOrgId);
            recursiveGetOrgId(lists, childOrgId);
        });
    }
}
